<?php
defined('IN_IA') or exit('Access Denied');


class bargain {

    public $error;




    /**
     * @param $member_id
     * @param $currency
     * @param int $type
     * @param string $remarks
     * @return bool
     */
    public function change_currency($member_id, $currency, $type = 1, $remarks = '')
    {
        if ($currency <= 0) {
            return true;
        }
        $currency_name = getConfig('currency_name', '金币');
        $member = p_get('member', array('id' => $member_id));
        if (empty($member)) {
            return true;
        }
        if (in_array($type, array(1, 2, 3, 4))) {
            $after_currency = $member['currency'] + $currency;

        } else {
            if ($member['currency'] < $currency) {
                $this->error = $currency_name . '不足';
                return false;
            }
            $after_currency = $member['currency'] - $currency;
        }

        $update = array('currency' => $after_currency);
        if (!p_update('member', $update, array('id' => $member_id))) {
            $this->error = $currency_name . '变更失败';
            return false;
        }

        $currency_log = array(
            'member_id' => $member_id,
            'currency' => $currency,
            'type' => $type,
            'same_day' => strtotime(date('Y-m-d')),
            'created' => time()
        );
        if ($remarks) {
            $currency_log['remarks'] = $remarks;
        }
        if (p_insert('currency_log', $currency_log)) {
            return true;
        }

        $this->error = '日志更新出错';
        return false;
    }


    /**
     * 更新当天
     * @param $member_id
     * @param $currency
     * @return bool
     */
    public function update_day($member_id, $currency, $type = 1)
    {
        $same_day = strtotime(date('Y-m-d'));
        $day = p_get('day', array('member_id' => $member_id, 'same_day' => $same_day));
        if (empty($day)) {
            $insert = array(
                'member_id' => $member_id,
                'same_day' => $same_day,
                'currency' => $currency,
                'updated' => time(),
                'created' => time(),
            );
            if ($type == 1) {
                $insert['clock'] = 1;
            }
            return p_insert('day', $insert);
        }
        $u = array(
            'currency' => $day['currency'] + $currency,
            'updated' => time()
        );
        if ($type == 1) {
            $u['clock'] = $day['clock'] + 1;
        }
        return p_update('day', $u, array('id' => $day['id']));
    }


    /**
     * @param $member_id
     * @return array|bool
     */
    public function get_clock_today($member_id)
    {
        $same_day = strtotime(date('Y-m-d'));
        $day = p_get('day', array('member_id' => $member_id, 'same_day' => $same_day));
        if (empty($day)) {
            $day = array(
                'member_id' => $member_id,
                'same_day' => $same_day,
                'clock' => 0,
                'currency' => 0,
                'updated' => time(),
                'created' => time(),
            );
            p_insert('day', $day);
        }
        $day['currency'] = floatval($day['currency']);
        return $day;
    }




    /**
     * 资金变动
     *
     * @param $member_id
     * @param $money
     * @param int $type
     * @return bool
     */
    public function change_money($member_id, $money, $type = 1)
    {
        if ($money <= 0) {
            return true;
        }
        $member = p_get('member', array('id' => $member_id));
        if (in_array($type, array(1, 2, 4, 5))) {
            $after_money = $member['money'] + $money;
        } else {

            if (intval($member['money'] * 100) < intval($money * 100)) {
                $this->error = '余额不足';
                return false;
            }
            $after_money = (intval($member['money'] * 100) - intval($money * 100)) / 100;
        }

        $update = array('money' => $after_money);
        if (!p_update('member', $update, array('id' => $member_id))) {
            $this->error = '余额变动失败';
            return false;
        }

        $money_log = array(
            'member_id' => $member_id,
            'money' => $money,
            'type' => $type,
            'after_money' => $after_money,
            'created' => time()
        );

        if (p_insert('money_log', $money_log)) {
            return true;
        }

        $this->error = '日志更新出错';
        return false;
    }






    /**
     * 用户活力币记录
     * @param $member_id
     * @param $p
     * @param int $page_size
     * @return array
     */
    public function currency_log($member_id, $p, $page_size = 10)
    {
        $limit = ($p - 1) * $page_size;
        $log = p_getall('currency_log', array('member_id' => $member_id), array(),'', array('id desc'), "{$limit}, {$page_size}");

        if ($log) {
            $types = array(
                1 => '兑换商品',
                2 => '自己生产',
                3 => '好友进贡',
                4 => '签到奖励',
                5 => '唤醒好友',
                6 => '完成任务',
                7 => '签到翻倍',
            );
            foreach ($log as & $value) {
                $value['remarks'] = $types[$value['type']];
                $value['mold'] = in_array($value['type'], array(2, 3, 4, 5, 6, 7)) ? 1 : 2;
                $value['createTime'] = date('Y.m.d', $value['created']);
            }
        }

        return $log;
    }


    /**
     * @param $money
     * @param string $member_id
     * @return bool
     */
    public function cash($money, $member_id = '')
    {
        $member = p_get('member', array('id' => $member_id));

        $MerchPay = new MerchPay();
        $trade_no = date("YmdHis", time()) . $member['id'] . rand(100, 999);
        $res = $MerchPay->pay($member['openid'], $trade_no, $money, ('来自'. getConfig('xcx_title') .'小程序提现'), '');//本机ip

        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {

            return true;
        }
        if ($_GET['dd']) {
            var_dump($res);
        }
        $this->error = isset($res[0]) ? $res[0] : '提现失败';
        return false;
    }


    /**
     *
     * @param $member_id
     * @param $fee_type
     * @param $memo
     * @param $cash_id
     * @return bool
     */
    public function qqCash($member_id, $fee_type, $memo = '', $cash_id = '')
    {
        $member = p_get('member', array('id' => $member_id));
        if (empty($memo)) {
            $memo = '(来自'. getConfig('xcx_title') .'小程序提现)';
        }
        $out_trade_no = date("YmdHis", time()) . $member['id'] . rand(100, 999);
        $data = array(
            'input_charset' => 'UTF-8',
            'openid'        => $member['openid'],
            'uin'           => $member['qq'],
            'mch_id'        => getConfig('qq_mch_id'),
            'nonce_str'     => $out_trade_no,
            'out_trade_no'  => $cash_id.substr($out_trade_no, 0 , 9),
            'fee_type'      => "CNY",
            'total_fee'     => (int)($fee_type * 100),
            'memo'          => $memo,
            'op_user_id'    => getConfig('op_user_id'),
            'op_user_passwd'=> md5(getConfig('op_user_passwd')),
            'spbill_create_ip' => CLIENT_IP,
        );
        $data['sign'] = qqAutograph($data);
        $s = $this->curl_post_ssl('https://api.qpay.qq.com/cgi-bin/epay/qpay_epay_b2c.cgi', $data);

        $result = json_decode(json_encode(simplexml_load_string($s, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            return true ;
        }

        $this->error = $result['err_code'] ;
        //$this->error = $result['err_code_desc'];
        return false;

    }


    /**
     * 企业付款发起请求
     * 此函数来自:https://pay.weixin.qq.com/wiki/doc/api/download/cert.zip
     */
    public function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()) {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //以下两种方式需选择一种
        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, getConfig('qq_apiclient_cert'));
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, getConfig('qq_apiclient_key'));

        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            //echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }


    /**
     * 生成支付订单
     * @param $member_id
     * @param $money
     * @param $relation_id
     * @param int $type
     * @return bool|string
     */
    public function unifiedOrder($member_id, $money, $relation_id, $type = 1)
    {
        $trade_no = date("YmdHis", time()) . $member_id . mt_rand(10000, 99999);
        $pay = array(
            'member_id' => $member_id,
            'trade_no' => $trade_no,
            'money' => $money,
            'relation_id' => $relation_id,
            'type' => $type,
            'created' => time()
        );

        if (p_insert('pay_order', $pay)) {
            return $trade_no;
        }
        return false;
    }


    /**
     *  随机字符串
     */
    public function out_trade_no()
    {
        $date = date('Ymd');
        $rand = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))),0,12);
        return $date . $rand . $this->getIssueNumber(12);
    }


    /**
     * @param $length
     * @return string
     */
    protected function getIssueNumber($length)
    {
        $str ='201812345678ab998c76541d230e7899a638k527d411236987412';
        $len =strlen($str)-1;
        $randStr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randStr .= $str[$num];
        }
        return $randStr;
    }




    /**
     * 获取广告
     * @param $position
     * @param array $limit
     * @return array|mixed
     */
    public function getAdvertisement($position, $limit = array())
    {
        if (!in_array($position, array(1))) {
            return ad(p_get('advertisement', array('position' => $position)));
        } else {
            $ad = p_getall('advertisement', array('position' => $position), array(), '', array('sort desc'), $limit);

            return empty($ad) ? array() : array_map('ad', $ad);
        }
    }


    /**
     * 砍价
     * @param $order_id
     * @param $member_id
     * @return bool|float|int
     */
    public function bargaining($order_id, $member_id)
    {
        $order = p_get('order', array('id' => $order_id));
        if (empty($order)) {
            $this->error = '砍价订单不存在';
            return false;
        }


        if ($order['status'] == 2) {
            $this->error = '砍价失败,订单已完成';
            return false;
        }
        if ($order['time_end'] < time() || $order['bargain'] >= $order['price']) {
            $this->error = '订单砍价已结束';
            return false;
        }

        if ($order['member_id'] != $member_id && $this->get_bargain_number($member_id) < 1) {
            $this->error = '今天的砍价次数已经使用完';
            return false;
        }

        if ($this->is_bargain($order_id, $member_id)) {
            return true;
        }


        $goods = p_get('goods', array('id' => $order['goods_id']));

        $after_money = $goods['in_after'];

        if ($order['member_id'] == $member_id) {
            $money = mt_rand($goods['own_start'] * 100, $goods['own_end'] * 100) / 100;

        } else {
            if ($this->is_old($member_id)) {

                if ($order['bargain'] >= $after_money) {
                    $money = mt_rand($goods['old_after_start'] * 100, $goods['old_after_end'] * 100) / 100;
                } else {
                    $money = mt_rand($goods['old_start'] * 100, $goods['old_end'] * 100) / 100;
                }

            } else {

                if ($order['bargain'] >= $after_money) {
                    $money = mt_rand($goods['new_after_start'] * 100, $goods['new_after_end'] * 100) / 100;
                } else {
                    $money = mt_rand($goods['new_start'] * 100, $goods['new_end'] * 100) / 100;
                }

            }
        }



        $surplus = $order['price'] - $order['bargain'];

        $money = $surplus > $money ? $money : $surplus;

        pdo_begin();
        try{
            if (!p_update('order', array('bargain' => $order['bargain'] + $money), array('id' => $order_id))) {
                throw new Exception('砍价失败,请稍后再试');
            }
            $insert = array(
                'member_id' => $member_id,
                'order_id' => $order_id,
                'goods_id' => $goods['id'],
                'money' => $money,
                'ip' => getip(),
                'equipment' => $_SERVER['HTTP_USER_AGENT'],
                'created' => time()
            );
            if (!p_insert('order_bargain', $insert)) {
                throw new Exception('砍价失败,请稍后再试');
            }
            pdo_commit();
            return $money;
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }

    }



    /**
     * 获取剩余砍价次数
     * @param $member_id
     * @return int
     */
    public function get_bargain_number($member_id)
    {
        $t = strtotime(date('Ymd'));

        $every_day_number = getConfig('every_day_number', 1);

        $sql = "SELECT COUNT(*) FROM " . prefix('order_bargain') . " WHERE member_id={$member_id} AND created>={$t}";
        $num = $every_day_number - (p_fetchcolumn($sql) ? : 0);

        return $num > 0 ? $num : 0;
    }


    /**
     * 是否给订单砍价过
     * @param $order_id
     * @param $member_id
     * @return bool
     */
    public function is_bargain($order_id, $member_id)
    {
        return p_get('order_bargain', array('order_id' => $order_id, 'member_id' => $member_id));
    }


    /**
     * 判断是否是老用户
     * @param $member_id
     * @return bool
     */
    public function is_old($member_id)
    {
        return p_getcolumn('order_bargain', array('member_id' => $member_id), 'count(*)') >= getConfig('old_bargain_number', 1);
    }


    /**
     * 获取砍价中的
     */
    public function get_bargain_by_id($member_id)
    {
        $sql = "SELECT * FROM " . prefix('order') . " WHERE member_id={$member_id} AND time_end <" . time() . ' limit 5';
        return  p_fetch($sql);
    }



    /**
     * 订单完成
     * @param $order_id
     * @return bool
     */
    public function buy($order_id)
    {
        $order = p_get('order', array('id' => $order_id, 'status' => 1));
        if (empty($order)) {
            $this->error = '订单不存在';
            return false;
        }

        pdo_begin();
        try{

            if ($order['integral'] > 0) {
                if (!$this->change_integral($order['member_id'], $order['integral'], 3)) {
                    throw new Exception($this->error);
                }
            }

            $address = p_get('address', array('member_id' => $order['member_id']));

            $update = array(
                'suc_time' => time(),
                'status' => 2,
                'type' => $order['price'] > $order['bargain'] ? 2 : 1,
                'address' => $address['address'],
                'name' => $address['name'],
                'phone' => $address['phone'],
            );

            if (!p_update('order', $update, array('id' => $order_id))) {
                throw new Exception('兑换失败');
            }

            $goods = p_get('goods', array('id' => $order['goods_id']));
            if (!p_update('goods', array('bargain_number' => $goods['bargain_number'] + 1), array('id' => $order['goods_id']))) {
                throw new Exception('兑换失败');
            }
            pdo_commit();
            return true;
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }



    /**
     * 积分变动
     * @param $member_id
     * @param $integral
     * @param int $type
     * @param string $remarks
     * @return bool
     */
    public function change_integral($member_id, $integral, $type = 1, $remarks = '')
    {
        if ($integral <= 0) {
            return true;
        }
        $integral_name = getConfig('integral_name', '积分');
        $member = p_get('member', array('id' => $member_id));
        if (in_array($type, array(1, 2, 4, 7, 8, 9))) {
            $after_integral = $member['integral'] + $integral;
        } else {

            if (intval($member['integral'] * 100) < intval($integral * 100)) {
                $this->error = $integral_name . '不足';
                return false;
            }
            $after_integral = (intval($member['integral'] * 100) - intval($integral * 100)) / 100;
        }

        $update = array('integral' => $after_integral);
        if (!p_update('member', $update, array('id' => $member_id))) {
            $this->error = $integral_name . '变动失败';
            return false;
        }

        $integral_log = array(
            'member_id' => $member_id,
            'integral' => $integral,
            'after_integral' => $after_integral,
            'type' => $type,
            'same_day' => strtotime(date('Y-m-d')),
            'created' => time()
        );
        if ($remarks) {
            $integral_log['remarks'] = $remarks;
        }
        if (p_insert('integral_log', $integral_log)) {
            return true;
        }

        $this->error = $integral_name . '日志更新出错';
        return false;
    }



    /**
     * 某天是否签到
     * @param int $member_id
     * @param string $same_day
     * @return bool
     */
    public function is_sign($member_id, $same_day = '')
    {
        if (empty($same_day)) {
            $same_day = strtotime(date('Y-m-d'));
        }
        return p_getcolumn('integral_log', array('member_id' => $member_id, 'same_day' => $same_day, 'type' => 1), 'COUNT(*)') > 0;
    }


    /**
     * 某天是否签到翻倍
     * @param int $member_id
     * @param string $same_day
     * @return bool
     */
    public function is_sign_double($member_id, $same_day = '')
    {
        if (empty($same_day)) {
            $same_day = strtotime(date('Y-m-d'));
        }
        return p_getcolumn('integral_log', array('member_id' => $member_id, 'same_day' => $same_day, 'type' => 2), 'COUNT(*)') > 0;
    }


    /**
     * 获取签到天数
     * @param $member_id
     * @return int
     */
    public function get_signin($member_id)
    {
        $signin = p_get('signin', array('member_id' => $member_id));
        if (empty($signin)) {
            return 0;
        }

        if ($signin['updated'] > strtotime(date('Y-m-d', time())) - 86400) {
            return $signin['days'];
        }
        return 0;
    }


    /**
     * 签到
     * @param $member_id
     * @return bool|int
     */
    public function signin($member_id, $integral)
    {
        try {
            pdo_begin();
            $sigin = p_get('signin', array('member_id' => $member_id));

            if (empty($sigin)) {
                $insert = array(
                    'member_id' => $member_id,
                    'days' => 1,
                    'all_sigin' => 1,
                    'updated' => time(),
                    'created' => time()
                );
                if (!p_insert('signin', $insert)) {
                    throw new Exception('签到失败,稍后再试');
                }
                $days = 1;
            } else {

                $today = strtotime(date('Y-m-d', time()));
                if ($sigin['updated'] >= $today) {
                    return $sigin['days'];
                }
                $update = array(
                    'all_sigin' => $sigin['all_sigin'] + 1,
                    'updated' => time()
                );
                if ($sigin['updated'] >= $today - 86400) {
                    $update['days'] = $sigin['days'] + 1;
                } else {
                    $update['days'] = 1;
                }

                if (!p_update('signin', $update, array('id' => $sigin['id']))) {
                    throw new Exception('签到失败,稍后再试');
                }
                $days = $update['days'];
            }

            if (!$this->change_integral($member_id, $integral, 1)) {
                throw new Exception($this->error);
            }
            pdo_commit();
            return $days;
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }


    /**
     *
     */
    public function receive($member_id, $red_bag_id)
    {
        $red_bag = p_get('red_bag', array('id' => $red_bag_id));
        if (empty($red_bag)) {
            $this->error = '红包不存在';
            return false;
        }
        $same_day = strtotime(date('Y-m-d'));
        $tody_number = p_getcolumn('red_bag', array('red_bag_id' => $red_bag_id, 'same_day' => $same_day), 'COUNT(*)') ? : 0;


        $red_grant_hour = getConfig('red_grant_hour');
        $red_grant_minute = getConfig('red_grant_minute');

        $h = date('H');
        $i = date('i');

        if ($red_grant_hour > $h || ($red_grant_hour == $h && $red_grant_minute > $i)) {
            $this->error = '红包还未发放,请' . $red_grant_hour . ':' . $red_grant_minute . '后来领取';
            return false;
        }

        if ($tody_number >= $red_bag['number']) {
            $this->error = '你来晚了,该红包已被抢光';
            return false;
        }

        if (p_get('member_red_bag', array('member_id' => $member_id, 'red_bag_id' => $red_bag_id, 'same_day' => $same_day))) {
            $this->error = '你已领取过了~';
            return false;
        }

        $member_number = p_getcolumn('member_red_bag', array('member_id' => $member_id, 'red_bag_id' => $red_bag_id), 'COUNT(*)');

        if ($member_number >= $red_bag['receive']) {
            $this->error = '你领取的数量已达到上限';
            return false;
        }
        if ($red_bag['sign_days'] > 0) {
            $signin = $this->get_signin($member_id);
            if ($signin < $red_bag['sign_days']) {
                $this->error = '需要连续签到' . $red_bag['sign_days'] . '天,才能领取该红包';
                return false;
            }
        }

        if (!$this->change_integral($member_id, $red_bag['integral'], 6)) {
            return false;
        }

        if ($red_bag['type'] == 1) {
            $money = $red_bag['money'];
        } else {
            $money = (mt_rand($red_bag['start'] * 100, $red_bag['end'] * 100)) / 100;
        }

        $member_red_bag = array(
            'member_id' => $member_id,
            'money' => $money,
            'red_bag_id' => $red_bag_id,
            'same_day' => $same_day,
            'created' => time()
        );
        if (!p_insert('member_red_bag', $member_red_bag)) {
            $this->error = '领取失败';
            return false;
        }

        if ($this->change_money($member_id, $money, 1)) {
            return $money;
        }
        return false;
    }



    /**
     * 完成邀请
     * @param $member_id
     * @param $share_id
     * @return bool
     */
    public function succ_share($member_id, $share_id)
    {
        $task = p_get('task', array('type' => 4));
        if (empty($task)) {
            return true;
        }

        $same_day = strtotime(date('Ymd'));
        /*
        $num = p_getcolumn('integral_log', array('member_id' => $member_id, 'type' => 9, 'same_day' => $same_day), 'COUNT(*)') ? : 0;
        if ($num >= $task['number']) {
            return true;
        }*/

        //todo 现在报错   p_getcolumn 改为P_get

        if (p_get('integral_log', array('member_id' => $member_id, 'type' => 9, 'remarks' => $share_id))) {
            return true;
        }


        $task_member = p_get('task_member', array('member_id' => $member_id, 'task_id' => $task['id'], 'same_day' => $same_day));

        pdo_begin();
        try{

            if ($task_member) {
                if ($task_member['number'] >= $task['number']) {
                    throw new Exception('奖励领取失败~');
                }

                if (!p_update('task_member', array('number' => $task_member['number'] + 1), array('id' => $task_member['id']))) {
                    throw new Exception('奖励领取失败~');
                }
            } else {
                $insert = array(
                    'member_id' => $member_id,
                    'task_id' => $task['id'],
                    'same_day' => $same_day,
                    'created' => time()
                );
                if (!p_insert('task_member', $insert)) {
                    throw new Exception('奖励领取失败~');
                }

            }
            if (!$this->change_integral($member_id, $task['integral'], 9, $share_id)) {
                throw new Exception('奖励领取失败~');
            }

            pdo_commit();
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }


    public function pdd_details($goods_id)
    {
        $pdd_pid = getConfig('pdd_pid');

        $url = 'http://gw-api.pinduoduo.com/api/router';
        $data = array(
            'type' =>  'pdd.ddk.goods.detail',
            'client_id' => getConfig('pdd_client_id'),
            'timestamp' => time(),
            'p_id' => $pdd_pid,
            'goods_id_list' => '[' . $goods_id . ']'
        );
        $data['sign'] = autograph($data);
        $data = json_decode(http_post($url, $data), true);//var_dump($data);
        $info = $data['goods_detail_response']['goods_details'][0];
        $info['coupon_start_time'] = date('m月d日', $info['coupon_start_time']);
        $info['coupon_end_time'] = date('m月d日', $info['coupon_end_time']);
        return $info;
    }
}